//
//  CMCTumblrRequestHelper.m
//  reacticons
//
//  Created by Nong Trung Nghia on 9/10/12.
//
//

#import "CMCTumblrRequestHelper.h"
#import "RequestHelper.h"
#import "Photo.h"
#import "DatabaseConnection.h"
#import "JSON.h"
#import "CMCOperationQueue.h"
#import "CMCUniqueArray.h"

#define HOST @"http://www.reacticons.com/api/read/json?type=photo"
#define ARG_TAGGED @"&tagged="
#define ARG_START @"&start="
#define ARG_QUANTITY @"&num="
#define MAX_QUANTITY 50

#define kTumblrRequestAllListPhotoSuccess @"kTumblrRequestAllListPhotoSuccess"
#define kTumblrRequestAllListPhotoFailure @"kTumblrRequestAllListPhotoFailure"

#define kTumblrRequestBlockPhotoSuccess @"kTumblrRequestBlockPhotoSuccess"
#define kTumblrRequestBlockPhotoFailure @"kTumblrRequestBlockPhotoFailure"

@implementation CMCTumblrRequestHelper
+(void)requestTumblrList{
//    NSString* urlString=[NSString stringWithFormat:@"%@%@0%@0",HOST,ARG_START,ARG_QUANTITY];
//    
//    [RequestHelper requestJSONWithURL:[NSURL URLWithString:urlString]
//                            andParams:nil
//      success:^(id result) {
//          [self requestTumblrListFromIndex:0 ];
//        
//      } failure:^(NSError *error) {
//          DBLOG(@"%@",[error localizedDescription]);
//      }];
    [[CMCOperationQueue sharedInstance] addOperation:[[NSInvocationOperation alloc] initWithTarget:[CMCTumblrRequestHelper class] selector:@selector(requestTumblrListFromIndex:) object:[NSNumber numberWithInt:0]]];
}
+(void)requestTumblrListFromIndex:(NSNumber*)index{
    DBLOG(@"CMCTumblrRequestHelper - requestTumblrListFromIndex - %d",index.intValue);
    NSString* urlString=[NSString stringWithFormat:@"%@%@%d%@50",HOST,ARG_START,index.intValue,ARG_QUANTITY];
    
    [RequestHelper requestJSONWithURL:[NSURL URLWithString:urlString]
                            andParams:nil
      success:^(id result) {
          DBLOG(@"CMCTumblrRequestHelper - requestTumblrListFromIndex - %d - Finish",index.intValue);
          NSString *resultString=[[[[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding] autorelease] substringFromIndex:22];
          resultString=[resultString substringToIndex:resultString.length-2];
          
          NSArray*list =[NSArray arrayWithArray:[(NSDictionary*)[resultString JSONValue] objectForKey:@"posts"]];
          if ([list count]>0) {
              NSMutableArray *itemList=[[[NSMutableArray alloc] init] autorelease];
              for (NSDictionary *item in list) {
                  Photo *photo=[[Photo alloc] init];
                  photo.photo100URL=[item objectForKey:@"photo-url-100"];
                  photo.photo75URL=[item objectForKey:@"photo-url-75"];
                  photo.photo250URL=[item objectForKey:@"photo-url-250"];
                  photo.photoImage=[item objectForKey:@"photo-url-1280"];
                  photo.photoThumbnail=[item objectForKey:@"photo-url-250"];
                  photo.photoCreatedDate=[item objectForKey:@"date-gmt"];
                  photo.photoID=[NSString stringWithFormat:@"%@",[item objectForKey:@"id"]];
                  photo.categoryName=[NSString stringWithFormat:@";%@;",[[item objectForKey:@"tags"] componentsJoinedByString:@";"]];
                  photo.photoName=[item objectForKey:@"photo-url-1280"];
                  photo.photoRecentlyUsed=@"19990102030405";
                  [itemList addObject:[photo itemObject]];
                  [photo release];
              }
              if ([DatabaseConnection updateListPhotos:itemList]>0) {
//                  [self requestTumblrListFromIndex:[NSNumber numberWithInt:index.intValue+50]];
                  [[CMCOperationQueue sharedInstance] addOperation:[[NSInvocationOperation alloc] initWithTarget:[CMCTumblrRequestHelper class] selector:@selector(requestTumblrListFromIndex:) object:[NSNumber numberWithInt:index.intValue+50]]];

              }
              else{
                  [[NSNotificationCenter defaultCenter] postNotificationName:kTumblrRequestAllListPhotoSuccess object:nil];
              }
              if (index.intValue==200) {
                  [[NSNotificationCenter defaultCenter] postNotificationName:kTumblrRequestBlockPhotoSuccess object:nil];
              }
          }
          else{
              [[NSNotificationCenter defaultCenter] postNotificationName:kTumblrRequestAllListPhotoSuccess object:nil];
          }

      } failure:^(NSError *error) {
          [[NSNotificationCenter defaultCenter] postNotificationName:kTumblrRequestAllListPhotoSuccess object:nil];

          DBLOG(@"requestTumblrListFromIndex - Fail - %d:%@",index.intValue,error.localizedDescription);
      }];
}

+(void)requestUpdateTumblrList{
//    [[CMCOperationQueue sharedInstance] addOperation:[[NSInvocationOperation alloc] initWithTarget:[CMCTumblrRequestHelper class] selector:@selector(requestUpdateTumblrList:) object:[NSNumber numberWithInt:0]]];
    [self requestUpdateTumblrListFromIndex:[NSNumber numberWithInt:0]];
}
+(void)requestUpdateTumblrListFromIndex:(NSNumber*)index{
    
    DBLOG(@"CMCTumblrRequestHelper - requestTumblrListFromIndex - %d",index.intValue);
    NSString* urlString=[NSString stringWithFormat:@"%@%@%d%@50",HOST,ARG_START,index.intValue,ARG_QUANTITY];
    
    [RequestHelper requestJSONWithURL:[NSURL URLWithString:urlString]
                            andParams:nil
      success:^(id result) {

          NSString *resultString=[[[[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding] autorelease] substringFromIndex:22];
          resultString=[resultString substringToIndex:resultString.length-2];
          
          NSArray*list =[NSArray arrayWithArray:[(NSDictionary*)[resultString JSONValue] objectForKey:@"posts"]];
          DBLOG(@"CMCTumblrRequestHelper - requestTumblrListFromIndex - %d - Finish:%d",index.intValue,list.count);
          if ([list count]>0) {
              CMCUniqueArray *uniqueArray=[[CMCUniqueArray alloc] init];
              
              if ([[NSUserDefaults standardUserDefaults] objectForKey:@"TAGS_ARRAY"]) {
                  for (id uItem in [[NSUserDefaults standardUserDefaults] objectForKey:@"TAGS_ARRAY"]) {
                      [uniqueArray addObject:uItem];
                  }
                  
              }
              
              NSMutableArray *itemList=[[[NSMutableArray alloc] init] autorelease];
              for (NSDictionary *item in list) {
                  Photo *photo=[[Photo alloc] init];
                  photo.photo100URL=[item objectForKey:@"photo-url-100"];
                  photo.photo75URL=[item objectForKey:@"photo-url-75"];
                  photo.photo250URL=[item objectForKey:@"photo-url-250"];
                  photo.photoImage=[item objectForKey:@"photo-url-1280"];
                  photo.photoThumbnail=[item objectForKey:@"photo-url-250"];
                  photo.photoCreatedDate=[item objectForKey:@"date-gmt"];
                  photo.photoID=[NSString stringWithFormat:@"%@",[item objectForKey:@"id"]];
                  photo.categoryName=[NSString stringWithFormat:@";%@;",[[item objectForKey:@"tags"] componentsJoinedByString:@";"]];
                  for (NSString *str in [item objectForKey:@"tags"]) {
                      [uniqueArray addObject:str];
                  }

                  photo.photoName=[item objectForKey:@"photo-url-1280"];
                  photo.photoRecentlyUsed=@"19990102030405";
                  [itemList addObject:[photo itemObject]];
                  [photo release];
              }
              
              [[NSUserDefaults standardUserDefaults] setObject:[uniqueArray sortedArray] forKey:@"TAGS_ARRAY"];
              [[NSUserDefaults standardUserDefaults] synchronize];
              
              [[NSOperationQueue currentQueue] addOperation:[[NSInvocationOperation alloc] initWithTarget:[DatabaseConnection class] selector:@selector(updateListPhotos:) object:itemList]];
              
              [self requestUpdateTumblrListFromIndex:[NSNumber numberWithInt:index.intValue+50]];
              
//              if (index.intValue==200) {
//                  [[NSNotificationCenter defaultCenter] postNotificationName:kTumblrRequestBlockPhotoSuccess object:nil];
//              }

          }
          else{
              [[NSNotificationCenter defaultCenter] postNotificationName:kTumblrRequestAllListPhotoSuccess object:nil];
          }
          
      } failure:^(NSError *error) {
          [[NSNotificationCenter defaultCenter] postNotificationName:kTumblrRequestAllListPhotoFailure object:nil];

          DBLOG(@"requestTumblrListFromIndex - Fail - %d:%@",index.intValue,error.localizedDescription);
      }];
}

@end
